<template>
    <div class="user-management-container">
        <div class="header-card">
            <h2>用户管理</h2>
            <p>管理系统用户，包括增删改查操作</p>
        </div>

        <el-card class="table-card" shadow="never">
            <div class="toolbar">
                <el-button type="primary" @click="addUser" icon="el-icon-plus">新增用户</el-button>
                <el-input v-model="searchKeyword" placeholder="搜索用户名或手机号" style="width: 300px; margin-left: 20px;"
                    clearable @keyup.enter="fetchData">
                    <template #append>
                        <el-button icon="el-icon-search" @click="fetchData"></el-button>
                    </template>
                </el-input>
            </div>

            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="username" label="用户名" min-width="120" />
                <el-table-column prop="phone" label="手机号" min-width="120" />
                <el-table-column prop="account" label="账号" min-width="120" />
                <el-table-column prop="balance" label="余额" min-width="100" align="center" />
                <el-table-column prop="create_time" label="创建时间" width="170" align="center">
                    <template #default="scope">{{ formatDate(scope.row.create_time) }}</template>
                </el-table-column>
                <el-table-column label="头像" width="100" align="center">
                    <template #default="scope">
                        <el-avatar :src="getImageUrl(scope.row.image_url)" v-if="scope.row.image_url"
                            size="small"></el-avatar>
                        <el-avatar v-else size="small">无</el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="editUser(scope.row)" plain round>编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteUser(scope.row)" plain round>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="handleDialogClose">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="用户名:" prop="username">
                            <el-input v-model="formData.username" placeholder="请输入用户名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号:" prop="phone">
                            <el-input v-model="formData.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账号:" prop="account">
                            <el-input v-model="formData.account" placeholder="请输入账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="余额:" prop="balance">
                            <el-input v-model="formData.balance" placeholder="请输入余额" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="密码:" prop="password" v-if="isAddMode">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
                </el-form-item>

                <el-form-item label="确认密码:" prop="confirmPassword" v-if="isAddMode">
                    <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
                </el-form-item>

                <el-form-item label="头像:" prop="image_url">
                    <el-upload class="avatar-uploader" action="http://localhost:8889/api/upload/header" method="post"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                        name="file">
                        <img v-if="formData.image_url" :src="getImageUrl(formData.image_url)" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)
const isAddMode = ref(true)

const baseUrl = 'http://localhost:8889' // 后端服务地址

const formData = reactive({
    id: '',
    username: '',
    phone: '',
    account: '',
    password: '',
    confirmPassword: '',
    balance: '',
    image_url: ''
})

const formRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== formData.password) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

const dialogTitle = computed(() => {
    return isAddMode.value ? '新增用户' : '编辑用户'
})

// 获取图片完整URL
const getImageUrl = (url) => {
    if (!url) return ''
    if (url.startsWith('http')) return url
    return `${baseUrl}${url}`
}

// 获取用户列表
const fetchData = async () => {
    loading.value = true
    try {
        const response = await axios.get(`${baseUrl}/api/admin/user/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                username: searchKeyword.value,
                phone: searchKeyword.value
            }
        })

        if (response.data.code === 200) {
            tableData.value = response.data.data
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取用户列表失败')
        }
    } catch (error) {
        ElMessage.error('获取用户列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const formatDate = (date) => {
    if (!date) return ''
    return date.replace('T', ' ').substring(0, 19)
}

const addUser = () => {
    isAddMode.value = true
    resetForm()
    dialogVisible.value = true
}

const editUser = (row) => {
    isAddMode.value = false
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除用户
const deleteUser = (row) => {
    ElMessageBox.confirm(
        `确定要删除用户"${row.username}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.delete(`${baseUrl}/api/admin/user/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('删除成功')
                fetchData()
            } else {
                ElMessage.error(response.data.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error('删除失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消删除
    })
}

const resetForm = () => {
    Object.assign(formData, {
        id: '',
        username: '',
        phone: '',
        account: '',
        password: '',
        confirmPassword: '',
        balance: '',
        image_url: ''
    })
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const handleDialogClose = (done) => {
    dialogVisible.value = false
    resetForm()
}

// 提交表单
const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                let response
                if (isAddMode.value) {
                    // 新增用户
                    response = await axios.post(`${baseUrl}/api/admin/user/addUser`, {
                        username: formData.username,
                        phone: formData.phone,
                        account: formData.account,
                        password: formData.password,
                        balance: formData.balance,
                        image_url: formData.image_url
                    })
                } else {
                    // 编辑用户
                    response = await axios.put(`${baseUrl}/api/admin/user/${formData.id}`, {
                        username: formData.username,
                        phone: formData.phone,
                        account: formData.account,
                        balance: formData.balance,
                        image_url: formData.image_url,
                        // 编辑时如果填写了密码，则更新密码
                        ...(formData.password && { password: formData.password })
                    })
                }

                if (response.data.code === 200) {
                    ElMessage.success(isAddMode.value ? '新增用户成功' : '编辑用户成功')
                    dialogVisible.value = false
                    fetchData()
                } else {
                    ElMessage.error(response.data.message || (isAddMode.value ? '新增用户失败' : '编辑用户失败'))
                }
            } catch (error) {
                ElMessage.error((isAddMode.value ? '新增用户失败' : '编辑用户失败') + ': ' + error.message)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 头像上传成功回调
const handleAvatarSuccess = async (response, uploadFile) => {
    if (response.code === 200) {
        formData.image_url = response.data.header_img_url
        ElMessage.success('头像上传成功')
    } else {
        ElMessage.error(response.message || '头像上传失败')
    }
}

// 头像上传前检查
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('头像图片大小不能超过 5MB!')
        return false
    }
    return true
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.user-management-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
    border-radius: 6px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>